/**
 * 
 */
package org.o14x.alpha.ui.commands;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Iterator;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.PlatformUI;
import org.o14x.alpha.Activator;
import org.o14x.alpha.preferences.PreferenceConstants;
import org.o14x.alpha.ui.controller.UIController;
import org.o14x.alpha.ui.views.folder.FolderView;
import org.o14x.alpha.ui.views.foldertree.FolderTreeView;

/**
 * SystemContextMenu Command
 * 
 * @author Olivier DANGREAUX
 */
public class SystemContextMenuCommand extends AbstractHandler {
	private UIController uiController;

	@SuppressWarnings("unchecked")
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String executableWithParams = Activator.getDefault().getPreferenceStore().getDefaultString(PreferenceConstants.SHELL_CONTEXT_MENU_EXECUTABLE);
		StringBuffer files = new StringBuffer();

		// gets the selection
		IStructuredSelection selection = null;
		if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart() instanceof FolderView) {
			selection = (IStructuredSelection) uiController.getDomain().getCurrentExplorerTab().getFolderView().getTableViewer().getSelection();
		} else if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart() instanceof FolderTreeView) {
			selection = (IStructuredSelection) uiController.getDomain().getCurrentExplorerTab().getExplorerTreeViewer().getSelection();
		}

		if (selection.isEmpty()) {
			File currentDirectory = uiController.getDomain().getCurrentExplorerTab().getFolder();
			files.append("\"" + currentDirectory + "\" "); //$NON-NLS-1$ //$NON-NLS-2$
		} else {
			for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
				File selectedFile = (File) iterator.next();
				files.append("\"" + selectedFile + "\" "); //$NON-NLS-1$ //$NON-NLS-2$
			}
		}

		try {
			Runtime.getRuntime().exec(MessageFormat.format(executableWithParams, new Object[] { files.toString() }));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Returns the value of uiController.
	 *
	 * @return The value of uiController.
	 */
	public UIController getUiController() {
		return uiController;
	}

	/**
	 * Sets the value of uiController.
	 *
	 * @param uiController The value of uiController to set.
	 */
	public void setUiController(UIController uiController) {
		this.uiController = uiController;
	}
}
